package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.api.vo.SkuLockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.SkuStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.vo.SkuPriceVo;
import com.spzx.product.vo.SkuStockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku库存表 服务实现类
 * </p>
 *
 * @author spzx
 * @since 2024-12-19
 */
@Service
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements SkuStockService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取sku库存信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuStockVo getSkuStock(Long skuId) {

        LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<SkuStock>()
                .eq(SkuStock::getSkuId, skuId)
                .select(SkuStock::getSkuId, SkuStock::getAvailableNum, SkuStock::getSaleNum);
        SkuStock skuStock = baseMapper.selectOne(queryWrapper);
        // 封装SkuStockVo
        SkuStockVo skuStockVo = new SkuStockVo();
        skuStockVo.setAvailableNum(skuStock.getAvailableNum());
        skuStockVo.setSaleNum(skuStock.getSaleNum());
        skuStockVo.setSkuId(skuId);

        return skuStockVo;
    }

    /**
     * 校验库存并锁定
     * @param orderNo
     * @param skuLockVoList
     * @return
     */
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        // 遍历所有商品
        skuLockVoList.forEach(
                skuLockVo -> {
                    Long skuId = skuLockVo.getSkuId();
                    Integer num = skuLockVo.getSkuNum();
                    // 校验库存是否足够
                    SkuStock checkResult = baseMapper.check(skuId, num);
                    if (checkResult == null) {
                        skuLockVo.setHaveStock(false);// 标记库存不足
                    } else {
                        skuLockVo.setHaveStock(true);// 标记库存足够
                    }
                });
        // 校验是否有库存不足的商品 通过过滤器筛选出库存不足的商品
        if (skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.isHaveStock())) {

            List<SkuLockVo> stockNotEnoughList = skuLockVoList
                    .stream()
                    .filter(skuLockVo -> !skuLockVo.isHaveStock())
                    .collect(Collectors.toList());
            //组装错误信息，提示商品库存不足
            StringBuilder errorMsg = new StringBuilder();//使用StringBuilder拼接错误信息
            stockNotEnoughList.forEach(
                    //查询现有库存量
                    skuLockVo -> {
                        errorMsg.append(skuLockVo.getSkuName()).append("\n");
                    });
            return errorMsg.append("库存不足").toString();
        } else {
            // 直接锁定库存
            skuLockVoList.forEach(skuLockVo -> {
                Long skuId = skuLockVo.getSkuId();
                Integer num = skuLockVo.getSkuNum();
                baseMapper.lock(skuId, num);
            });
        }
        String dataKey = "sku:lock:data:" + orderNo;
        redisTemplate.opsForValue().set(dataKey, skuLockVoList);
        return "";
    }

    /**
     * 解锁库存
     * @param orderNo
     */
    @Override
    public void unlock(String orderNo) {
        //幂等性处理
        String key = "sku:unlock:" + orderNo;
        Boolean isFirst = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 10, TimeUnit.MINUTES);
        if (!isFirst) return;//不是第一次锁定，直接返回 防止重复提交

        //锁定库存的缓存数据
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);

        //校验数据是否为空
        if (!CollectionUtils.isEmpty(skuLockVoList)) {
            //解锁库存
            for (SkuLockVo skuLockVo : skuLockVoList) {
                Long skuId = skuLockVo.getSkuId();
                Integer num = skuLockVo.getSkuNum();
                baseMapper.unlock(skuId, num);
            }
            //删除缓存数据
            redisTemplate.delete(dataKey);
        }

    }

    /**
     * 扣减库存
     * @param orderNo
     */
    @Override
    public void minus(String orderNo) {

        //幂等性处理
        String key = "sku:minus:" + orderNo;
        //业务去重，防止重复消费
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if(!isExist) return;

        // 获取锁定库存的缓存信息
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)this.redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)){
            return ;
        }

        // 减库存
        skuLockVoList.forEach(skuLockVo -> {
            Integer row = baseMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
        });

        // 扣减库存之后，删除锁定库存的缓存。
        this.redisTemplate.delete(dataKey);
    }
}
